import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  // 启用实验性功能
  experimental: {
    optimizePackageImports: ['antd', 'zustand'],
    turbo: {
      rules: {
        '*.svg': {
          loaders: ['@svgr/webpack'],
          as: '*.js',
        },
      },
    },
  },

  // 代码分割配置
  webpack: (config, { dev, isServer }) => {
    // 基础配置，移除复杂的医学影像库依赖
    config.resolve.fallback = {
      fs: false,
      path: false,
    }

    // 生产环境优化
    if (!dev && !isServer) {
      // 分割第三方库
      config.optimization.splitChunks = {
        chunks: 'all',
        cacheGroups: {
          // React 相关库
          react: {
            name: 'react',
            test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
            priority: 20,
            chunks: 'all',
          },
          // Ant Design
          antd: {
            name: 'antd',
            test: /[\\/]node_modules[\\/](@ant-design|antd)[\\/]/,
            priority: 15,
            chunks: 'all',
          },
          // 状态管理
          state: {
            name: 'state',
            test: /[\\/]node_modules[\\/](zustand)[\\/]/,
            priority: 10,
            chunks: 'all',
          },
          // 其他第三方库
          vendor: {
            name: 'vendor',
            test: /[\\/]node_modules[\\/]/,
            priority: 5,
            chunks: 'all',
            minChunks: 2,
          },
        },
      }

      // 压缩配置
      config.optimization.minimize = true
    }

    return config
  },

  // API 代理配置
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: process.env.BACKEND_URL + '/api/:path*',
      },
    ]
  },

  // 图片优化
  images: {
    domains: ['localhost'],
    formats: ['image/webp', 'image/avif'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },

  // 压缩配置
  compress: true,

  // 环境变量
  env: {
    BACKEND_URL: process.env.BACKEND_URL || 'http://localhost:8000',
  },

  // 性能预算
  onDemandEntries: {
    maxInactiveAge: 25 * 1000,
    pagesBufferLength: 2,
  },
};

export default nextConfig;
